package com.wujige.doc;

import com.wujige.utils.ClinetUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * 批量操作测试
 *
 * @author: lipan
 * @date: 2021/4/27 20:12
 */

public class DocBatchOperationTest {


    RestHighLevelClient client = null;


    @Before
    public void OpenConection(){
        client= ClinetUtils.getClient();
    }

    @After
    public void closeConnection(){
        ClinetUtils.close();
    }

    /**
     * 批量新增
     *
     * @throws Exception
     */
    @Test
    public void testBatchCreate() throws Exception {



        BulkRequest request = new BulkRequest();

        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan","age",20,"sex","男"));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi","age",30,"sex","男"));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu","age",50,"sex","女"));
        request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "tom","age",25,"sex","男"));
        request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "tony","age",10,"sex","男"));
        request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "橘右京","age",102,"sex","男"));
        request.add(new IndexRequest().index("user").id("1007").source(XContentType.JSON, "name", "jack","age",56,"sex","男"));
        request.add(new IndexRequest().index("user").id("1008").source(XContentType.JSON, "name", "pony","age",52,"sex","男"));
        request.add(new IndexRequest().index("user").id("1009").source(XContentType.JSON, "name", "lily","age",27,"sex","女"));



        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);


        System.out.println("took:" + responses.getTook());
        System.out.println("items:" + responses.getItems());

    }


    /**
     * 测试批量删除
     * @throws Exception
     */
    @Test
    public void testBatchDelete() throws Exception{


        //创建批量删除请求对象
        BulkRequest request = new BulkRequest();

        request.add(new DeleteRequest().index("user").id("1001"));
        request.add(new DeleteRequest().index("user").id("1002"));
        request.add(new DeleteRequest().index("user").id("1003"));

        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);

        System.out.println("took:" + responses.getTook());
        System.out.println("items:" + responses.getItems());

    }



}
